package tgc.edu.zz.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.zz.custom.AjaxResult;
import tgc.edu.zz.custom.DataGridParam;
import tgc.edu.zz.custom.DataGridUtils;
import tgc.edu.zz.entity.Permission;
import tgc.edu.zz.form.PermissionForm;
import tgc.edu.zz.service.PermissionService;


/**
 * 权限管理controller
 * @author zz
 *
 */
@Controller
@RequestMapping("/permission")
public class PermissionController {
	@Autowired
	private PermissionService permissionService;
	
	@RequestMapping("/manage")
	public String page() {
		return "permission/manage";
	}
	
	@RequestMapping(value = "/page")
	@ResponseBody
	public Object page(DataGridParam param, PermissionForm form) {
		Pageable pageable = param.getPageable();
		Specification<Permission> spec = buildSpec(form);
		Page<Permission> page = permissionService.findAll(spec, pageable);
		return DataGridUtils.getPageResult(page);
	}

	private Specification<Permission> buildSpec(PermissionForm form) {
		Specification<Permission> spec = new Specification<Permission>() {

			@Override
			public Predicate toPredicate(Root<Permission> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				String name = form.getName();
				if (StringUtils.hasText(name)) {
					rules.add(cb.like(root.get("name"), "%"+name+"%"));
				}
				String code = form.getCode();
				if (StringUtils.hasText(code)) {
					rules.add(cb.equal(root.get("code"), "%"+code+"%"));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}
	
	@RequestMapping(value = "/save")
	@ResponseBody
	public Object save(PermissionForm form) {
		Permission per = new Permission();
		per.setName(form.getName());
		per.setCode(form.getCode());
		permissionService.save(per);
		return new AjaxResult(true, "新增成功");
	}
}
